<?php

namespace app\wechat\controller;

use think\Config;
use think\Db;
use app\enumerations\CustomerAccountLogTypeEnum;
use app\enumerations\PointDetailTypeEnum;
use app\enumerations\IsTopEnum;
use app\enumerations\IsSaleEnum;

class Goods extends Common {

    use WechatTrait;

    /**
     * 商品列表
     * @return \think\response\Json
     */
    public function goodsList() {

        $currentCustomer = $this->request->currentCustomer;
        $pageNum = $this->request->post('pageNum');
        $pageSize = $this->request->post('pageSize');
        $keyword = $this->request->post("keyword");

        // 定义返回数据
        $returnData['list'] = [];

        $stockList = $this->stockService->getStockListForPage(
            $currentCustomer['id'], $pageNum, $pageSize, $keyword);

        if (!count($stockList)) {
            return successReturn($returnData);
        }

        // 拼接商品ID字符串
        $goodsIds = '';
        foreach ($stockList as $key=>$val) {
            $goodsIds .= $val['goods_id'].',';
        }
        $goodsIds = substr($goodsIds, 0, strlen($goodsIds)-1);

        $yxGoodsResult = getYxGoodsSearchList(1, count($stockList),
            '', $goodsIds);

        if(!$yxGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxGoodsResult["msg"];
            return json($returnError);
        }

        foreach ($stockList as $key=>$val) {

            $info = [];
            foreach ($yxGoodsResult['list']['list'] as $k=>$v) {

                if ($val['goods_id'] == $v['goodsId']) {

                    $info['goods_id'] = $v['goodsId'];
                    $info['goods_name'] = $v['goodsName'];
                    $info['goods_img'] = $v['goodsImg'];
                    $info['favorite_num'] = $v['favoriteNum'];
                    $info['market_price'] = $v['marketPrice'];
                    $info['shop_price'] = $v['shopPrice'];
                    $info['commission'] = $v['commission'];
                    $info['little_desc'] = $val['little_desc'];
                    $info['is_top'] = $val['is_top'];

                    // 判断是否为拼团商品  如果是则显示拼团价格
                    if($v['isPintuan'] == 1) {
                        $info['shop_price'] = $v['tuanPrice'];
                    }

                }
            }

            if (!isNullOrEmpty($info)) {
                $returnData['list'][$key] = $info;
            }
        }

        return successReturn($returnData);

    }

    /**
     * 商品分类列表
     * @return \think\response\Json
     */
    public function goodsCatList() {

        $currentCustomer = $this->request->currentCustomer;

        $yxResult = getYxGoodsCatsList();

        if(!$yxResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxResult["msg"];
            return json($returnError);
        }

        // 一级分类
        $oneLevelList = [];
        foreach ($yxResult['list'] as $key=>$val) {

            // 如果parentId等于0 表示为一级分类
            if ($val['parentId'] == 0) {

                $info['cat_id'] = $val['catId'];
                $info['cat_name'] = $val['catName'];

                array_push($oneLevelList, $info);
            }
        }

        $returnData['info']['headimgurl'] = $currentCustomer['headimgurl'];
        $returnData['info']['background_image'] = $currentCustomer['background_image']
            .config('constants.ossProcessResizeH');
        $returnData['list'] = $oneLevelList;

        return successReturn($returnData);

    }

    /**
     * 整理货架
     * @return \think\response\Json
     */
    public function arrangeGoods() {

        $currentCustomer = $this->request->currentCustomer;
        $catId = $this->request->post("catId");

        $todayArrange = $this->goodsArrangeService
            ->checkTodayArrange($currentCustomer['id']);

        // 如果今天没整理过货架
        if (isNullOrEmpty($todayArrange)) {

            Db::startTrans();
            try {

                // 整理货架记录
                $goodsArrangeData['customer_id'] = $currentCustomer['id'];
                $goodsArrangeData['add_point'] = config('constants.likeReceiveAddPoint');
                $goodsArrangeData['create_date'] = date("Y-m-d");

                $saveGoodsArrange = $this->goodsArrangeService->saveByData($goodsArrangeData);

                // 整理货架获得积分LOG
                $customerAccountLogData['customer_id'] = $currentCustomer['id'];
                $customerAccountLogData['refer_customer_id'] = $currentCustomer['id'];
                $customerAccountLogData['type'] = CustomerAccountLogTypeEnum::getEnumValue(CustomerAccountLogTypeEnum::ARRANGEGOODS_CODE);
                $customerAccountLogData['value'] = config('constants.likeReceiveAddPoint');
                $customerAccountLogData['refer_id'] = $saveGoodsArrange['id'];

                $this->customerAccountLogService->saveByData($customerAccountLogData);

                // 增加积分流水
                $pointDetailData['point'] = config('constants.likeReceiveAddPoint');
                $pointDetailData['type'] = PointDetailTypeEnum::getEnumValue(PointDetailTypeEnum::ARRANGEGOODS_CODE);
                $pointDetailData['customer_id'] = $currentCustomer['id'];
                $pointDetailData['refer_id'] = $saveGoodsArrange['id'];
                $pointDetailData['refer_customer_id'] = $currentCustomer['id'];
                $pointDetailData['refer_customer_nickname'] = $currentCustomer['nickname'];
                $pointDetailData['refer_customer_headimgurl'] = $currentCustomer['headimgurl'];

                $this->pointDetailService->saveByData($pointDetailData);

                // 增加积分
                $customerData['history_point'] = $currentCustomer['history_point']
                    + config('constants.likeReceiveAddPoint');
                $customerData['total_point'] = $currentCustomer['history_point']
                    + config('constants.likeReceiveAddPoint');

                $this->customerService->updateByIdAndData($currentCustomer['id'], $customerData);

                Db::commit();

            } catch(\PDOException $e) {

                Db::rollback();

                return errorReturn('errorWechat.errorService');
            }
        }

        // 定义返回数据
        $returnData['list'] = [];

        //我所拥有的
        $stockList = $this->stockService->getStockListByCatId(
            $currentCustomer['id'], $catId);

        //我们库中拥有的
        $goodsList = $this->goodsService->getGoodsListByCatId($catId);

        if (!count($goodsList)) {
            return successReturn($returnData);
        }

        // 拼接商品ID字符串
        $goodsIds = '';
        // 拼接商品兑换消耗积分
        $exchangeConsumePointList = [];
        foreach ($goodsList as $key=>$val) {

            $goodsIds .= $val['goods_id'].',';

            $exchangeConsumePointList[$val['goods_id']] = $val['point'];
        }
        $goodsIds = substr($goodsIds, 0, strlen($goodsIds)-1);

        // 每日优选的
        $yxGoodsResult = getYxGoodsSearchList(1, count($goodsList), '', $goodsIds);

        if(!$yxGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxGoodsResult["msg"];
            return json($returnError);
        }

        $returnData['list'] = [];
        foreach ($yxGoodsResult['list']['list'] as $key=>$val) {

            $info['goods_id'] = $val['goodsId'];
            $info['goods_name'] = $val['goodsName'];
            $info['goods_image'] = $val['goodsImg'];
            $info['shop_price'] = $val['shopPrice'];
            $info['market_price'] = $val['marketPrice'];
            $info['favorite_num'] = $val['favoriteNum'];
            $info['little_desc'] = $val['littleDesc'];
            $info['is_sale'] = $val['isSale'];
            $info['commission'] = $val['commission'];
            $info['point'] = $exchangeConsumePointList[$val['goodsId']];
            $info['is_exist'] = false;
            $info['top_time'] = '';
            $info['is_top'] = 0;
            $info['xd_id'] = 0;

            // 判断是否为拼团商品  如果是则显示拼团价格
            if($val['isPintuan'] == 1) {
                $info['shop_price'] = $val['tuanPrice'];
            }

            foreach ($stockList as $k=>$v) {

                if ($val['goodsId'] == $v['goods_id']) {

                    $info['little_desc'] = $v['little_desc'];
                    $info['is_sale'] = $v['is_sale'];
                    $info['is_exist'] = true;
                    $info['top_time'] = $v['top_time'];
                    $info['is_top'] = $v['is_top'];
                }
            }

            foreach ($goodsList as $k=>$v) {

                if ($val['goodsId'] == $v['goods_id']) {
                    $info['xd_id'] = $v['id'];
                }
            }

            $returnData['list'][$key] = $info;
        }

        // 数组排序
        array_multisort(array_column($returnData['list'],
            'is_top'),SORT_DESC,$returnData['list']);
        array_multisort(array_column($returnData['list'],
            'top_time'),SORT_DESC,$returnData['list']);
        array_multisort(array_column($returnData['list'],
            'xd_id'),SORT_DESC,$returnData['list']);

        return successReturn($returnData);

    }

    /**
     * 置顶商品
     * @return \think\response\Json
     */
    public function topGoods() {

        $currentCustomer = $this->request->currentCustomer;
        $goodsId = $this->request->post("goodsId");
        $isTop = $this->request->post("isTop");

        if (!checkEnumValue($isTop, IsTopEnum::getAllList())) {
            return errorReturn('errorWechat.errorGoodsIsTopValue');
        }

        $stock = $this->stockService->findByCustomerIdAndGoodsId(
            $currentCustomer['id'], $goodsId);

        if (isNullOrEmpty($stock)) {
            return errorReturn('errorWechat.errorGoodsNotFound');
        }

        Db::startTrans();
        try {

            // 更新我的商品
            $stockData['is_top'] = $isTop;
            $stockData['top_time'] = date("Y-m-d H:i:s");

            $this->stockService->updateByIdAndData($stock['id'], $stockData);

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn('errorWechat.errorService');

        }

        return successReturn();

    }

    /**
     * 修改商品描述
     * @return \think\response\Json
     */
    public function updateGoodsLittleDesc() {

        $currentCustomer = $this->request->currentCustomer;
        $goodsId = $this->request->post("goodsId");
        $littleDesc = $this->request->post("littleDesc");

        $stock = $this->stockService->findByCustomerIdAndGoodsId(
            $currentCustomer['id'], $goodsId);

        if (isNullOrEmpty($stock)) {
            return errorReturn('errorWechat.errorGoodsNotFound');
        }

        $stockData['little_desc'] = $littleDesc;

        $this->stockService->updateByIdAndData($stock['id'], $stockData);

        return successReturn();

    }

    /**
     * 上下架商品
     * @return \think\response\Json
     */
    public function saleGoods() {

        $currentCustomer = $this->request->currentCustomer;
        $goodsId = $this->request->post("goodsId");
        $isSale = $this->request->post("isSale");

        if (!checkEnumValue($isSale, IsSaleEnum::getAllList())) {
            return errorReturn('errorWechat.errorGoodsIsSaleValue');
        }

        $stock = $this->stockService->findByCustomerIdAndGoodsId(
            $currentCustomer['id'], $goodsId);

        if (isNullOrEmpty($stock)) {
            return errorReturn('errorWechat.errorGoodsNotFound');
        }

        Db::startTrans();
        try {

            // 更新我的商品
            $stockData['is_sale'] = $isSale;

            $this->stockService->updateByIdAndData($stock['id'], $stockData);

            $this->calculationMyGoodsCatJson();

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn('errorWechat.errorService');

        }

        return successReturn();

    }

    /**
     * 解锁商品
     * @return \think\response\Json
     */
    public function unlockGoods() {

        $currentCustomer = $this->request->currentCustomer;
        $goodsId = $this->request->post("goodsId");

        $goods = $this->goodsService->findByGoodsId($goodsId);

        if (isNullOrEmpty($goods)) {
            return errorReturn('errorWechat.errorGoodsNotFound');
        }

        $stock = $this->stockService->findByCustomerIdAndGoodsId(
            $currentCustomer['id'], $goodsId);

        if (!isNullOrEmpty($stock)) {
            return errorReturn('errorWechat.errorStockExist');
        }

        // 判断金币是否足够解锁
        if ($currentCustomer['total_point'] < $goods['point']) {
            return errorReturn('errorWechat.errorTotalPointNotEnough');
        }

        $yxGoodsResult = getYxGoodsSearchList(1, 1, '', $goodsId);

        if(!$yxGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["msg"] = $yxGoodsResult["msg"];
            return json($returnError);
        }

        if (!count($yxGoodsResult['list']['list'])) {
            return errorReturn('errorWechat.errorGoodsNotFound');
        }
        $yxGoodsDetail = $yxGoodsResult['list']['list'][0];

        Db::startTrans();
        try {

            // 我的商品仓库数据
            $goodsCatIdPath = explode('_', $yxGoodsDetail['goodsCatIdPath']);
            $stockData['cat_id'] = $goodsCatIdPath[0];
            $stockData['customer_id'] = $currentCustomer['id'];
            $stockData['goods_id'] = $goodsId;
            $stockData['cost_point'] = $goods['point']*(-1);
            $stockData['little_desc'] = $yxGoodsDetail['littleDesc'];

            $saveStockRes = $this->stockService->saveByData($stockData);

            // 解锁商品减去积分LOG
            $customerAccountLogData['customer_id'] = $currentCustomer['id'];
            $customerAccountLogData['refer_customer_id'] = $currentCustomer['id'];
            $customerAccountLogData['type'] = CustomerAccountLogTypeEnum::getEnumValue(CustomerAccountLogTypeEnum::UNLOCKNEWGOODS_CODE);
            $customerAccountLogData['value'] = $goods['point']*(-1);
            $customerAccountLogData['refer_id'] = $saveStockRes['id'];

            $this->customerAccountLogService->saveByData($customerAccountLogData);

            // 金币流水
            $pointDetailData['point'] = $goods['point']*(-1);
            $pointDetailData['customer_id'] = $currentCustomer['id'];
            $pointDetailData['refer_id'] = $saveStockRes['id'];
            $pointDetailData['refer_customer_id'] = $currentCustomer['id'];
            $pointDetailData['refer_customer_nickname'] = $currentCustomer['nickname'];
            $pointDetailData['refer_customer_headimgurl'] = $currentCustomer['headimgurl'];
            $pointDetailData['type'] = PointDetailTypeEnum::getEnumValue(PointDetailTypeEnum::UNLOCKNEWGOODS_CODE);

            $this->pointDetailService->saveByData($pointDetailData);

            // 用户数据
            $customerData['total_point'] = $currentCustomer['total_point']
                - $goods['point'];
            $this->customerService->updateByIdAndData($currentCustomer['id'],
                $customerData);

            $this->calculationMyGoodsCatJson();

            Db::commit();

        } catch(\PDOException $e) {

            Db::rollback();

            return errorReturn('errorWechat.errorService');

        }

        return successReturn();

    }

    /**
     * 我的货架
     * @return \think\response\Json
     */
    public function myShelf() {

        $currentCustomer = $this->request->currentCustomer;

        // 小店推荐商品 小店推荐商品分类ID是 -2
        $recommendGoodsResult = getYxGoodsSearchList(
            1, 10, '-2', '');

        if(!$recommendGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["msg"] = $recommendGoodsResult["msg"];
            return json($returnError);
        }

        $recommendGoodsList = [];
        foreach ($recommendGoodsResult['list']['list'] as $key=>$val) {

            $recommendGoodsInfo['goods_id'] = $val['goodsId'];
            $recommendGoodsInfo['goods_name'] = $val['goodsName'];
            $recommendGoodsInfo['goods_img'] = $val['goodsImg'];
            $recommendGoodsInfo['favorite_num'] = $val['favoriteNum'];
            $recommendGoodsInfo['market_price'] = $val['marketPrice'];
            $recommendGoodsInfo['shop_price'] = $val['shopPrice'];
            $recommendGoodsInfo['commission'] = $val['commission'];
            $recommendGoodsInfo['little_desc'] = $val['littleDesc'];

            // 判断是否为拼团商品  如果是则显示拼团价格
            if($val['isPintuan'] == 1) {
                $recommendGoodsInfo['shop_price'] = $val['tuanPrice'];
            }

            array_push($recommendGoodsList, $recommendGoodsInfo);
        }

        // 如果我的商品分类json为空
        if (isNullOrEmpty($currentCustomer['own_goods_cat_json'])) {

            $currentCustomer['own_goods_cat_json'] = $this->calculationMyGoodsCatJson();
        }

        $ownGoodsCatList = json_decode($currentCustomer['own_goods_cat_json'], true);
        foreach ($ownGoodsCatList as &$val) {

            $val['goods_list'] = [];

            if ($val['cat_id'] == '-2') {
                $val['goods_list'] = $recommendGoodsList;
            }
        }

        // 已解锁商品数
        $unlockGoodsCount = $this->stockService
            ->countByCustomerId($currentCustomer['id']);

        // 在销售中商品数
        $saleGoodsCount = $this->stockService
            ->countValidByCustomer($currentCustomer['id']);

        $returnData['info'] = $this->baseCustomerInfo();
        $returnData['info']['customer_id'] = $currentCustomer['id'];
        $returnData['unlock_goods_count'] = $unlockGoodsCount;
        $returnData['sale_goods_count'] = $saleGoodsCount;
        $returnData['cat_list'] = $ownGoodsCatList;

        return successReturn($returnData);

    }

    /**
     * 根据分类搜索我的货架
     * @return \think\response\Json
     */
    public function searchMyShelfByCatId() {

        $currentCustomer = $this->request->currentCustomer;
        $catId = $this->request->post("catId");

        // 定义返回数据
        $returnData['list'] = [];

        $stockList = $this->stockService->getSaleStockListByCatId(
            $currentCustomer['id'], $catId);

        if (!count($stockList)) {
            return successReturn($returnData);
        }

        // 拼接商品ID字符串
        $goodsIds = '';
        foreach ($stockList as $key=>$val) {
            $goodsIds .= $val['goods_id'].',';
        }
        $goodsIds = substr($goodsIds, 0, strlen($goodsIds)-1);

        $yxGoodsResult = getYxGoodsSearchList(1, count($stockList),
            '', $goodsIds);

        if(!$yxGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxGoodsResult["msg"];
            return json($returnError);
        }

        foreach ($stockList as $key=>$val) {

            $info = [];
            foreach ($yxGoodsResult['list']['list'] as $k=>$v) {

                if ($val['goods_id'] == $v['goodsId']) {

                    $info['goods_id'] = $v['goodsId'];
                    $info['goods_name'] = $v['goodsName'];
                    $info['goods_img'] = $v['goodsImg'];
                    $info['favorite_num'] = $v['favoriteNum'];
                    $info['market_price'] = $v['marketPrice'];
                    $info['shop_price'] = $v['shopPrice'];
                    $info['commission'] = $v['commission'];
                    $info['little_desc'] = $val['little_desc'];
                    $info['is_top'] = $val['is_top'];

                    // 判断是否为拼团商品  如果是则显示拼团价格
                    if($v['isPintuan'] == 1) {
                        $info['shop_price'] = $v['tuanPrice'];
                    }

                }
            }

            if (!isNullOrEmpty($info)) {
                $returnData['list'][$key] = $info;
            }
        }

        return successReturn($returnData);

    }

    /**
     * 根据分类搜索我的货架
     * @return \think\response\Json
     */
    public function searchMyShelfByGoodsName() {

        $currentCustomer = $this->request->currentCustomer;
        $pageNum = $this->request->post("pageNum");
        $pageSize = $this->request->post("pageSize");
        $goodsName = $this->request->post("goodsName");

        // 定义返回数据
        $returnData['list'] = [];

        $stockList = $this->stockService->getStockListForPage(
            $currentCustomer['id'], $pageNum, $pageSize, $goodsName);

        if (!count($stockList)) {
            return successReturn($returnData);
        }

        // 拼接商品ID字符串
        $goodsIds = '';
        foreach ($stockList as $key=>$val) {
            $goodsIds .= $val['goods_id'].',';
        }
        $goodsIds = substr($goodsIds, 0, strlen($goodsIds)-1);

        $yxGoodsResult = getYxGoodsSearchList(1, count($stockList),
            '', $goodsIds);

        if(!$yxGoodsResult["success"]) {
            $returnError = config("errorWechat.errorYxService");
            $returnError["message"] = $yxGoodsResult["msg"];
            return json($returnError);
        }

        foreach ($stockList as $key=>$val) {

            $info = [];
            foreach ($yxGoodsResult['list']['list'] as $k=>$v) {

                if ($val['goods_id'] == $v['goodsId']) {

                    $info['goods_id'] = $v['goodsId'];
                    $info['goods_name'] = $v['goodsName'];
                    $info['goods_img'] = $v['goodsImg'];
                    $info['favorite_num'] = $v['favoriteNum'];
                    $info['market_price'] = $v['marketPrice'];
                    $info['shop_price'] = $v['shopPrice'];
                    $info['commission'] = $v['commission'];
                    $info['little_desc'] = $val['little_desc'];
                    $info['is_top'] = $val['is_top'];

                    // 判断是否为拼团商品  如果是则显示拼团价格
                    if($v['isPintuan'] == 1) {
                        $info['shop_price'] = $v['tuanPrice'];
                    }

                }
            }

            if (!isNullOrEmpty($info)) {
                $returnData['list'][$key] = $info;
            }
        }

        return successReturn($returnData);

    }

}